<template>
  <!-- 日期选择弹框 -->
  <uni-popup ref="datePopup" type="bottom">
    <view class="date-picker-modal">
      <view class="picker-header">
        <text class="picker-cancel" @click="close">取消</text>
        <text class="picker-title">{{ title }}</text>
        <text class="picker-confirm" @click="confirmDate">确认</text>
      </view>

      <!-- 年月日滚轮选择器 -->
      <picker-view
        class="picker-view"
        :value="pickerValue"
        @change="pickerChange"
        :indicator-style="indicatorStyle"
      >
        <picker-view-column>
          <view v-for="year in years" :key="year" class="picker-item">
            {{ year }}年
          </view>
        </picker-view-column>
        <picker-view-column>
          <view v-for="month in months" :key="month" class="picker-item">
            {{ month }}月
          </view>
        </picker-view-column>
        <picker-view-column>
          <view v-for="day in days" :key="day" class="picker-item">
            {{ day }}日
          </view>
        </picker-view-column>
      </picker-view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  title: {
    type: String,
    default: "选择开始日期",
  },
});

const emit = defineEmits(["update:modelValue", "confirm"]);

// 弹框引用
const datePopup = ref(null);

// 临时选中的日期
const tempDate = ref("");

// 年月日数据
const years = ref([]);
const months = ref([]);
const days = ref([]);
const pickerValue = ref([0, 0, 0]);
const indicatorStyle = "height: 50px;";

// 当前选中日期文本
const currentDateText = computed(() => {
  if (!tempDate.value) return "请选择日期";
  return tempDate.value;
});

// 对外暴露方法
const open = () => {
  tempDate.value = props.modelValue || getToday();
  setPickerByDate(tempDate.value);
  datePopup.value?.open();
};

const close = () => {
  datePopup.value?.close();
};

defineExpose({ open, close });

// 初始化年月日
const initData = () => {
  const now = new Date();
  const currentYear = now.getFullYear();
  years.value = [];
  // 从1920年到当前年份+50年
  for (let y = 1920; y <= currentYear + 50; y++) {
    years.value.push(y);
  }
  months.value = Array.from({ length: 12 }, (_, i) =>
    String(i + 1).padStart(2, "0")
  );
};

onMounted(() => {
  initData();
  const initDate = props.modelValue || getToday();
  setPickerByDate(initDate);
});

// 滚轮变化
const pickerChange = (e) => {
  const [yIdx, mIdx, dIdx] = e.detail.value;
  const year = years.value[yIdx];
  const month = Number(months.value[mIdx]);

  // 重建天数
  const numDays = new Date(year, month, 0).getDate();
  days.value = Array.from({ length: numDays }, (_, i) =>
    String(i + 1).padStart(2, "0")
  );
  const safeDayIdx = Math.min(dIdx, days.value.length - 1);
  pickerValue.value = [yIdx, mIdx, safeDayIdx];

  tempDate.value = `${year}-${String(month).padStart(2, "0")}-${
    days.value[safeDayIdx]
  }`;
};

// 将滚轮同步到指定日期
const setPickerByDate = (dateStr) => {
  const [yStr, mStr, dStr] = (dateStr || getToday()).split("-");
  const year = Number(yStr);
  const month = Number(mStr);
  const day = Number(dStr);

  const numDays = new Date(year, month, 0).getDate();
  days.value = Array.from({ length: numDays }, (_, i) =>
    String(i + 1).padStart(2, "0")
  );

  const yIdx = years.value.findIndex((y) => y === year);
  const mIdx = months.value.findIndex(
    (m) => m === String(month).padStart(2, "0")
  );
  const dIdx = Math.min(
    days.value.findIndex((d) => d === String(day).padStart(2, "0")),
    days.value.length - 1
  );
  if (yIdx !== -1 && mIdx !== -1 && dIdx !== -1) {
    pickerValue.value = [yIdx, mIdx, dIdx];
  }
  tempDate.value = dateStr;
};

// 确认选择
const confirmDate = () => {
  emit("update:modelValue", tempDate.value);
  emit("confirm", tempDate.value);
  close();
};

// 获取今天日期
const getToday = () => {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(now.getDate()).padStart(2, "0")}`;
};
</script>

<style lang="scss" scoped>
.date-picker-modal {
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.picker-cancel,
.picker-confirm {
  font-size: 28rpx;
  color: #ffa726;
}

.picker-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.picker-view {
  height: 400rpx;
  padding: 0 32rpx 32rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  line-height: 50px;
  font-size: 32rpx;
  color: #333;
}
</style>
